package com.yowasa.xiuxian.engine.message.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruiyun.jvppeteer.util.StringUtil;
import com.yowasa.xiuxian.annoations.CMD;
import com.yowasa.xiuxian.engine.CommonEngine;
import com.yowasa.xiuxian.engine.item.ItemInterface;
import com.yowasa.xiuxian.engine.message.CmdMessageHandler;
import com.yowasa.xiuxian.entity.bo.item.EmailItem;
import com.yowasa.xiuxian.entity.bo.item.UserItemBo;
import com.yowasa.xiuxian.entity.bo.user.UserBO;
import com.yowasa.xiuxian.entity.enums.CmdScopeEnum;
import com.yowasa.xiuxian.entity.enums.QualityEnum;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.entity.po.XiuxianUserEmail;
import com.yowasa.xiuxian.exception.HandlerException;
import com.yowasa.xiuxian.service.helper.EmailHelper;
import com.yowasa.xiuxian.service.helper.ItemHelper;
import com.yowasa.xiuxian.service.helper.MessageHelper;
import com.yowasa.xiuxian.service.helper.UserHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@CMD(name = "/邮箱", scope = CmdScopeEnum.ALL)
public class UserEmailHandler extends CmdMessageHandler {

    @Autowired
    private MessageHelper messageHelper;
    @Autowired
    private UserHelper userHelper;
    @Autowired
    private EmailHelper emailHelper;
    @Autowired
    private ItemHelper itemHelper;

    public static final Logger logger = LoggerFactory.getLogger(UserEmailHandler.class);

    @Override
    @Transactional
    public void execute(SendMessage message) {
        UserBO user = userHelper.checkOpUser(message);
        List<String> params = getAllParam(message);

        if (StringUtils.isEmpty(params.get(0))) {
            messageHelper.replyMys(message, "可以在后面追加 列表 查看 收取 发送 一键 等二级指令进行后续操作");
            return;
        }
        if ("列表".equals(params.get(0))) {
            List<XiuxianUserEmail> emails = new ArrayList<>();
            if (params.size() >= 2) {
                emails = emailHelper.selectAllEmaliByUserId(user.getId());
            } else {
                emails = emailHelper.selectEmaliByUserId(user.getId());
            }
            StringBuffer sb = new StringBuffer();
            sb.append("/邮箱 列表 历史 可查看过往邮件，否则只查看未读和未领取附件的邮件\n");
            sb.append("邮件编号        邮件标题     是否有附件未领取\n");
            for (XiuxianUserEmail email : emails) {
                String a = email.getItemStatus() == 0 ? "有附件" : "无附件";
                sb.append(email.getId()).append("   ").append("[").append(email.getTitle()).append("]").append("    ").append(a).append("\n");
            }
            messageHelper.replyMys(message, sb.toString());
        }
        if ("查看".equals(params.get(0))) {
            try {
                int i = Integer.parseInt(params.get(1));
                XiuxianUserEmail email = emailHelper.selectById(i);
                if (!email.getAccountId().equals(user.getId())) {
                    messageHelper.replyMys(message, "不是你的邮件哦");
                    return;
                }
                StringBuffer sb = new StringBuffer();
                sb.append("[").append(email.getTitle()).append("]\n").append(email.getMsg());
                email.setReadStatus(1);
                emailHelper.update(email);
                messageHelper.replyMys(message, sb.toString());
            } catch (Exception e) {
                throw new HandlerException("指令格式为 /邮箱 查看 编号");
            }
        }
        //398要收取的邮件id为 ： 170
        //XiuxianUserEmail(id=170, accountId=398, readStatus=0, itemStatus=0, title=全服补偿, msg=因公式问题导致先前版本的土修与金修过于弱势，现对攻击与物抗进行了补正，法攻法抗也增加了气感补正，补偿全服玩家一颗脱胎换骨丹，可重置升级属性, extra={"num":"1","name":"脱胎换骨丹","type":"1","quality":2}, fromAccount=0, createTime=Tue Aug 01 16:05:39 CST 2023)
        if ("收取".equals(params.get(0))) {
            try {
                int i = Integer.parseInt(params.get(1));
                XiuxianUserEmail email = emailHelper.selectByIdForUpdate(i);
                logger.info("{}要收取的邮件id为 ： {}", user.getId(), i);
                logger.info("邮件详情为：{}", email);
                if (!email.getAccountId().equals(user.getId())) {
                    messageHelper.replyMys(message, "不是你的邮件哦");
                    return;
                }
                if (email.getItemStatus() == 1) {
                    messageHelper.replyMys(message, "你已经收取了这封邮件的附件啦");
                    return;
                }
                //附件字符串 [{type,name,num,quality}]
                //"["type":1,"name":"金疮药","num":10,"quality":2]"
                JSONObject jsonObject = JSONUtil.parseObj(email.getExtra());
                EmailItem emailItem = JSONUtil.toBean(jsonObject, EmailItem.class);
                ItemInterface itemInterface = CommonEngine.ITEM_MAP.get(emailItem.getName());
                if (emailItem.getType() == 3) {
                    itemHelper.addEquip(user, itemInterface, emailItem.getNum(), emailItem.getQuality());
                } else if (emailItem.getType() == 0) {
                    user.getUserConfig().setGold(user.getUserConfig().getGold() + emailItem.getNum());
                    userHelper.saveUserInfo(user);
                } else {
                    itemHelper.addItem(user, itemInterface, emailItem.getNum());
                }
                email.setItemStatus(1);
                emailHelper.update(email);
                messageHelper.replyMys(message, MessageFormat.format("你收取了[{0}]*{1}", emailItem.getName(), emailItem.getNum()));
            } catch (Exception e) {
                throw new HandlerException("指令格式为 /邮箱 收取 编号");
            }
        }
        if ("发送".equals(params.get(0))) {
            // /邮箱 发送 物品 数量 @
            if(params.size() < 2){
                throw new HandlerException("请输入要发送的物品和数量，无数量默认为1\n正确指令格式为 /邮箱 发送 物品 数量 @对象\n请以空格分割每个次级指令，且@对象需在最后\n如果发送的是装备，数量的位置应该为品质，且装备一次只能发送一件");
            }
            String atUserId = messageHelper.getMysContentAtUserId(message.getContent());
            if (StringUtil.isEmpty(atUserId)) {
                throw new HandlerException("需要at对方才能发邮件");
            }
            UserBO byUserId = userHelper.getByUserId(atUserId);
            if (byUserId == null) {
                throw new HandlerException("对方未创建角色，无法给他发邮件");
            }

            ItemInterface itemInterface = CommonEngine.ITEM_MAP.get(params.get(1));
            if(itemInterface == null){
                throw new HandlerException("不存在这样的物品");
            }
            if(itemInterface.getType().getId() == 3){
                String itemName = params.get(1);
                String quality = params.get(2);
                QualityEnum qualityEnum = QualityEnum.getByName(quality);
                UserItemBo myItem = itemHelper.getMyEqip(user.getId(),itemName,qualityEnum.getId());
                if (myItem == null) {
                    messageHelper.replyMys(message, MessageFormat.format("背包中没有名为[{0}]的装备", itemName));
                    return;
                }
                itemHelper.dropItem(myItem, 1);
                XiuxianUserEmail email = new XiuxianUserEmail(byUserId.getId());
                email.setFromAccount(user.getId());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type",itemInterface.getType().getId());
                jsonObject.put("name",itemInterface.getName());
                jsonObject.put("num",1);
                jsonObject.put("quality",qualityEnum.getId());
                email.setExtra(jsonObject.toString());
                email.setTitle("玩家邮件发送");
                email.setMsg("收到了"+user.getName()+"发送的邮件，物品为"+itemName);
                emailHelper.insert(email);

            }else {
                int num = com.yowasa.xiuxian.util.StrUtil.checkAndConvert2Int(params.get(2), "数量");

                UserItemBo myItem = itemHelper.getMyItem(user.getId(), itemInterface.getName());
                if (myItem == null) {
                    throw new HandlerException("你身上未持有该道具:" + itemInterface.getName());
                }
                if (myItem.getItemNum() < num) {
                    throw new HandlerException(MessageFormat.format("你身上道具[{0}]持有数量为{1},不足{2}", itemInterface.getName(), myItem.getItemNum(), num));
                }
                //身上道具移除
                itemHelper.dropItem(myItem, num);
                XiuxianUserEmail email = new XiuxianUserEmail(byUserId.getId());
                email.setFromAccount(user.getId());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type",itemInterface.getType().getId());
                jsonObject.put("name",itemInterface.getName());
                jsonObject.put("num",num);
                jsonObject.put("quality",2);
                email.setExtra(jsonObject.toString());
                email.setTitle("玩家邮件发送");
                email.setMsg("收到了"+user.getName()+"发送的邮件，物品为"+itemInterface.getName());
                emailHelper.insert(email);
            }
            messageHelper.replyMys(message,"发送成功");
        }
        if ("一键".equals(params.get(0))) {
            List<XiuxianUserEmail> emailList = emailHelper.selectEmaliByUserId(user.getId());
            List<XiuxianUserEmail> collect = emailList.stream().filter(e -> e.getItemStatus() == 0).collect(Collectors.toList());
            List<String> reply = new ArrayList<>();
            reply.add("正在开始一键领取邮件");
            for (XiuxianUserEmail e : collect){
                JSONObject jsonObject = JSONUtil.parseObj(e.getExtra());
                EmailItem emailItem = JSONUtil.toBean(jsonObject, EmailItem.class);
                ItemInterface itemInterface = CommonEngine.ITEM_MAP.get(emailItem.getName());
                if (emailItem.getType() == 3) {
                    itemHelper.addEquip(user, itemInterface, emailItem.getNum(), emailItem.getQuality());
                } else if (emailItem.getType() == 0) {
                    user.getUserConfig().setGold(user.getUserConfig().getGold() + emailItem.getNum());
                    userHelper.saveUserInfo(user);
                } else {
                    itemHelper.addItem(user, itemInterface, emailItem.getNum());
                }
                String format = MessageFormat.format("你收取了[{0}]*{1}", emailItem.getName(), emailItem.getNum());
                reply.add(format);
            }
            reply.add("一键领取结束");
            emailHelper.updateStatusByUser(user.getId());
            messageHelper.replyMys(message, StrUtil.join("\n",reply));
        }
    }


    public String desc() {
        return new StringBuffer().append("邮件相关的指令，大更新或更新补偿，都会通过邮件发给玩家\n")
                .toString();

    }
}
